package com.douya.pangu.application.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import com.douya.common.pojo.vo.CommonResponseVO;
import com.douya.pangu.core.api.sys.fegin.CoreUserFeign;
import com.douya.pangu.core.api.sys.fegin.UserDetailsImpl;
import com.douya.pangu.core.api.sys.pojo.vo.CoreUserVO;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author hcy
 * @date 2019-11-22 16:26
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    CoreUserFeign coreUserFeign;

    @Override
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
        Long userId = Long.valueOf(id);
        CommonResponseVO<CoreUserVO> coreUserData = coreUserFeign.findById(userId);
        if (Objects.isNull(coreUserData) || Objects.isNull(coreUserData.getData())) {
            throw new UsernameNotFoundException("用户不存在");
        }
        CoreUserVO coreUser = coreUserData.getData();
        CommonResponseVO<List<String>> userPermissionData = coreUserFeign.userPermissionList(userId);
        List<String> permissionList = userPermissionData.getData();
        return new UserDetailsImpl(
                String.valueOf(coreUser.getId()),
                coreUser.getUserName(),
                coreUser.getLoginPassword(),
                CollectionUtil.isEmpty(permissionList) ? Collections.emptyList() :
                        permissionList.parallelStream()
                                .map(SimpleGrantedAuthority::new)
                                .collect(Collectors.toList())
        );
    }
}
